#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Send a message to the specific phone using Aliyun SMS.
'''

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.profile import region_provider
from app.util import SendSmsRequest
import uuid
import random
from config import ACCESS_KEY_ID, ACCESS_KEY_SECRET, SIGN_NAME, TEMPLATE_CODE
from app.util.RedisClient import set_cache_key_value, get_cache_key_value

# Do NOT change the REGION.
REGION = "cn-hangzhou"
PRODUCT_NAME = "Dysmsapi"
DOMAIN = "dysmsapi.aliyuncs.com"

# create a client
acs_client = AcsClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET, REGION)
region_provider.add_endpoint(PRODUCT_NAME, REGION, DOMAIN)


def _send_sms(business_id, phone_numbers, sign_name, template_code, template_param=None):
	# The obj.实例对象
	smsRequest = SendSmsRequest.SendSmsRequest()

	# The Template Code is necessary.短信模板编码
	smsRequest.set_TemplateCode(template_code)

	# The Template parameters are necessary.短信模板参数
	if template_param is not None:
		smsRequest.set_TemplateParam(template_param)

	# The request number is necessary.业务请求流水号
	smsRequest.set_OutId(business_id)

	# The sign name is necessary.短信签名
	smsRequest.set_SignName(sign_name)

	# The destnation phone number is necessary.短信发送的号码列表
	smsRequest.set_PhoneNumbers(phone_numbers)

	# Call the sms sending interface. Return json.调用短信发送接口，返回json
	smsResponse = acs_client.do_action_with_exception(smsRequest)

	return smsResponse


def send_sms(phone):
	def _code():
		return random.randint(100000, 999999)

	def __business_id():
		return uuid.uuid1()

	code = get_cache_key_value(phone)
	if code is None:
		code = _code()
	params = "{\"code\":\"%s\"}" % (code)
	_business_id = __business_id()
	resp = _send_sms(_business_id, phone, SIGN_NAME, TEMPLATE_CODE, params)
	respon = eval(resp)
	set_cache_key_value(phone, code, 400)
	if respon["Code"] == "OK":
		return {"errcode": 200, "errmsg": respon["Message"]}
	if respon["Code"] == "isv.BUSINESS_LIMIT_CONTROL":
		return {"errcode": 400, "errmsg": "您发送过于频繁,请稍后再发！"}
	return {"errcode": respon["Code"], "errmsg": respon["Message"]}
